// pages/statistics/statistics.js
var wxCharts = require('../../wx-charts/wx-chart-min');
import Butils from '../../utils/detailsUtil'
var app = getApp();
var lineChart = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statisticTypeList: [
      {
        label: "年",
        value: "0"
      },
      {
        label: "月",
        value: "1"
      },
      // {
      //   label: "日",
      //   value: "2"
      // }
    ],
    selectStatisticType: {},
    statisticTypeIndex: 0,
    yearList: [],
    yearIndex: 0,
    monthList: [],
    monthIndex: 0,
    dayList: [],
    dayIndex: 0,
    dataSR: {},
    dataZC: {},
    dateArr: []
  },
  touchHandler: function (e) {
    lineChart.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        return category + ' '
          + item.name + ':' + item.data
      }
    });
  },
  createSimulationData: function () {
    var categories = [];
    var data = [];
    for (var i = 0; i < 10; i++) {
      categories.push('2016-' + (i + 1));
      data.push(Math.random() * (20 - 10) + 10);
    }
    // data[4] = null;
    return {
      categories: categories,
      data: data
    }
  },
  setSimulationData: function (type, index) {
    if (type == 0) {
      Butils.statisticsDetailByYear(app.globalData.wxUserInfo.id, this.data.yearList[index].year, (res) => {
        this.setStatisticsData(res.data.objects)
      })
    } else if (type == 1) {
      Butils.statisticsDetailByMonth(app.globalData.wxUserInfo.id, this.data.monthList[index].year, this.data.monthList[index].month, (res) => {
        this.setStatisticsData(res.data.objects)
      })
    } else {
      Butils.statisticsDetailByDay(app.globalData.wxUserInfo.id,
        this.data.dayList[index].year,
        this.data.dayList[index].month,
        this.data.dayList[index].day, (res) => {
          this.setStatisticsData(res.data.objects)
        })
    }
  },
  /**
   * 整理统计数据
   */
  setStatisticsData: function (data) {
    var srD = []
    var srS = []
    var zcD = []
    var zcS = []
    var dateArr = []
    for (let i = 0; i < data.length; i++) {
      const element = data[i];
      if (this.data.statisticTypeIndex == 0) {
        var index = dateArr.indexOf(element.year + "-" + element.month)
        if (index == -1) {
          dateArr.push(element.year + "-" + element.month)
          if (element.bill_type.is_income) {
            srS.push(Number(element.amount))
            zcS.push(0)
          } else {
            zcS.push(Number(element.amount))
            srS.push(0)
          }
        } else {
          if (element.bill_type.is_income) {
            srS[index] += Number(element.amount)
          } else {
            zcS[index] += Number(element.amount)
          }
        }
      } else if (this.data.statisticTypeIndex == 1) {
        var index = dateArr.indexOf(element.year + "-" + element.month + "-" + element.day)
        if (index == -1) {
          dateArr.push(element.year + "-" + element.month + "-" + element.day)
          if (element.bill_type.is_income) {
            srS.push(Number(element.amount))
            zcS.push(0)
          } else {
            zcS.push(Number(element.amount))
            srS.push(0)
          }
        } else {
          if (element.bill_type.is_income) {
            srS[index] += Number(element.amount)
          } else {
            zcS[index] += Number(element.amount)
          }
        }
      }
      this.setData({
        dateArr: dateArr
      })
    }
    this.setData({
      dataSR: {
        categories: dateArr,
        data: srS
      },
      dataZC: {
        categories: dateArr,
        data: zcS
      }
    })
    this.updateData(dateArr)
  },
  updateData: function (dateArr) {
    var windowWidth = '', windowHeight = '';    //定义宽高
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth / 750 * 690;  //以设计图750为主进行比例算换
      windowHeight = res.windowWidth / 750 * 550    //以设计图750为主进行比例算换
    } catch (options) {
      console.error('getSystemInfoSync failed!');
    }
    lineChart = new wxCharts({
      canvasId: 'lineCanvas',
      type: 'line',//图标展示的类型有:'line','pie','column','area','ring','radar'
      categories: dateArr,
      animation: true,
      background: '#F1F1F1',
      series: [{
        name: '支出',
        data: this.data.dataZC.data,
        format: function (val, name) {
          return parseFloat(Number(val)).toFixed(2)
        }
      }, {
        name: '收入',
        data: this.data.dataSR.data,
        format: function (val, name) {
          return parseFloat(Number(val)).toFixed(2)
        }
      }],
      xAxis: {
        disableGrid: false,//是否隐藏x轴分割线
      },
      yAxis: {
        title: '金额 (元)',
        min: 0
      },
      width: windowWidth,  //图表展示内容宽度
      height: windowHeight,  //图表展示内容高度
      dataLabel: false,  //是否在图表上直接显示数据
      dataPointShape: true, //是否在图标上显示数据点标志
      extra: {
        lineStyle: 'curve'//曲线
      }
    });
  },
  /**
   * 类型选择
   * @param {}} e 
   */
  CheckChange: function (e) {
    this.setData({
      statisticTypeIndex: e.detail.index,
      selectStatisticType: e.detail.item
    })
    if (this.data.statisticTypeIndex == 2) {
      this.setSimulationData(this.data.statisticTypeIndex, this.data.dayIndex);
      this.setData({
        yearIndex: 0,
        monthIndex: 0
      })
    } else if (this.data.statisticTypeIndex == 1) {
      this.setSimulationData(this.data.statisticTypeIndex, this.data.monthIndex);
      this.setData({
        yearIndex: 0,
        dayIndex: 0
      })
    } else {
      this.setSimulationData(this.data.statisticTypeIndex, this.data.yearIndex);
      this.setData({
        monthIndex: 0,
        dayIndex: 0
      })
    }
  },
  repeatDate: function (array) {
    var arr = [];    //定义一个临时数组 
    for (var i = 0; i < array.length; i++) {    //循环遍历当前数组 
      //判断当前数组下标为i的元素是否已经保存到临时数组 
      //如果已保存，则跳过，否则将此元素保存到临时数组中 
      if (JSON.stringify(arr).indexOf(JSON.stringify(array[i])) == -1) {
        arr.push(array[i]);
      }
    }
    return arr;
  },
  /**
   * 初始化日列表
   */
  setDayList: function () {
    Butils.selectDetailDate(app.globalData.wxUserInfo.id, 0, (res) => {
      var arr = this.repeatDate(res.data.objects);
      this.setData({
        dayList: arr,
        dayIndex: 0
      })
    })
  },
  /**
   * 初始化月列表
   */
  setMonthList: function () {
    Butils.selectDetailDate(app.globalData.wxUserInfo.id, 1, (res) => {
      var arr = this.repeatDate(res.data.objects);
      this.setData({
        monthList: arr,
        monthIndex: 0
      })
    })
  },
  /**
   * 初始化年列表
   */
  setYearList: function () {
    Butils.selectDetailDate(app.globalData.wxUserInfo.id, 2, (res) => {
      var arr = this.repeatDate(res.data.objects);
      this.setData({
        yearList: arr,
        yearIndex: 0
      })
      this.setSimulationData(this.data.statisticTypeIndex, this.data.yearIndex);
    })
  },
  /**
   * 时间选择
   * @param {}} e 
   */
  daySelect: function (e) {
    if (this.data.statisticTypeIndex == 2) {
      this.setData({
        dayIndex: e.currentTarget.dataset.index,
      })
    } else if (this.data.statisticTypeIndex == 1) {
      this.setData({
        monthIndex: e.currentTarget.dataset.index,
      })
    } else {
      this.setData({
        yearIndex: e.currentTarget.dataset.index
      })
    }
    this.setSimulationData(this.data.statisticTypeIndex, e.currentTarget.dataset.index);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {



  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.setDayList();
    this.setMonthList();
    this.setYearList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})